﻿using System.Threading.Tasks;
using System.Web.Mvc;
using CkSoftware.GroupMe.Sdk.Core.Exceptions;
using CkSoftware.GroupMe.Sdk.Helpers.Authorization;
using CkSoftware.GroupMe.Sdk.Helpers.Users;
using CkSoftware.GroupMe.Sdk.TestWeb.Models;

namespace CkSoftware.GroupMe.Sdk.TestWeb.Controllers
{
    public class ClientAuthController : Controller
    {
		public ActionResult Index()
        {
	        var model = new ClientAuthConfigurationModel
		        {
			        RecommendedUrl = Url.Action("AuthCallback", "ClientAuth", null, Request.Url != null ? Request.Url.Scheme : string.Empty, Request.Url != null ? Request.Url.Host : string.Empty)
		        };

			return View(model);
        }

		public ActionResult ConfigureClientAuth(ClientAuthConfigurationModel model)
		{
			if (ModelState.IsValid)
			{
				var authHelper = new GroupMeClientAuthHelper();
				var redirectModel = new AuthRedirectModel
					{
						RedirectUrl = authHelper.GetAuthenticationRedirectUrl(model.ClientId)
					};

				return View("AuthRedirect", redirectModel);
			}

			return View("Index", model);
		}

		public async Task<ActionResult> AuthCallback()
		{
			var authHelper = new GroupMeClientAuthHelper();
			var model = new AuthCallbackModel();

			try
			{
				model.AccessToken = authHelper.GetAccessTokenForAuthorizeRequest(Request);

				if (!string.IsNullOrEmpty(model.AccessToken))
				{
					var apiAccess = authHelper.GetWebApiAccessForAccessToken(model.AccessToken);
					var userHelper = new UserHelper(apiAccess);
					model.CurrentUser = await userHelper.GetCurrentUser();
				}
			}
			catch (GroupMeException)
			{}

			return View(model);
		}
    }
}
